package softswitch.agi;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.ejb.Stateless;

import org.asteriskjava.fastagi.AgiChannel;
import org.asteriskjava.fastagi.AgiException;
import org.asteriskjava.fastagi.AgiRequest;
import org.asteriskjava.fastagi.BaseAgiScript;


@Stateless
public class ValidatePassword extends BaseAgiScript {
	
	
	public void service(AgiRequest request, AgiChannel channel) throws AgiException {


		answer();
		
		Integer tries = 0;
		Boolean valid = false;
		String password;
		
		while(true){
			if(tries == 0){
				password = getData("password/password",10000,6);
				valid = isValidPassword(password);
			}
			else{
				
			}
			
			
			if(valid){
				exec("Playback","auth-thankyou");
				break;
			}
			else{					
				exec("Playback","auth-incorrect");
				if(tries==3){
					exec("Playback","vm-goodbye");
					hangup();
					break;
				}
				tries++;
			}										
			
		}

	
		
		
	}//service()
	
	public Boolean isValidPassword(String password){
		
		Boolean result = false;
		
		try{
			Class.forName("org.postgresql.Driver");
		}
		catch(ClassNotFoundException e){
			System.out.println("E1");
		}
		
		Connection con = null;		
		try{
			con = DriverManager.getConnection("jdbc:postgresql://192.168.14.4:5432/asterisk360","postgres","postgres");
		}
		catch(SQLException e){
			e.printStackTrace();
			System.out.println("Error Connect");
		}
		
		if(con != null){
			
			try {
				String sql = "SELECT COUNT(*) FROM softswitch.circuit WHERE code = "+ password+ " ; ";
				Statement stmt = con.createStatement();
				ResultSet rs = stmt.executeQuery(sql);
				rs.next();
				Integer out = rs.getInt(1);
				
				if(out > 0){
					result = true;
				}			
				con.close();
			}
			catch (SQLException e) {
				e.printStackTrace();
			}			
			
		}
		
		return result;
		
	}
	

	
}// Class
